package com.itic.mall.system.msg.apppush.service;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;
import com.itic.appbase.framework.common.basevo.ReturnVo;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.AlertType;
import com.itic.appbase.framework.type.ReadType;
import com.itic.appbase.framework.utils.JPushUtils;
import com.itic.mall.mobile.msg.vo.MsgVO;
import com.itic.mall.system.inter.msg.apppush.persistence.dao.AppPushDao;
import com.itic.mall.system.inter.msg.apppush.persistence.model.AppPush;
import com.itic.mall.system.inter.msg.apppush.persistence.model.AppPushExample;
import com.itic.mall.system.inter.msg.apppush.persistence.model.AppPushExample.Criteria;
import com.itic.mall.system.inter.msg.type.persistence.model.MsgType;
import com.itic.mall.system.inter.project.jgset.persistence.dao.JgsetDao;
import com.itic.mall.system.inter.project.jgset.persistence.model.Jgset;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.msg.type.service.MsgTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class AppPushService
     extends CrudService<AppPushDao,AppPush,AppPushExample> {
    @Autowired
    private AppPushDao appPushDao;
    @Autowired
    private JgsetDao jgsetDao;
    @Autowired
    private MsgTypeService msgTypeService;
    

    /**
     * 推送APP消息给用户
     * @param user
     * @param text
     * @return
     */
    public String push( UsersMall user, String text ){
    	ReturnVo returnVo = new ReturnVo();
    	returnVo.setStatus(FAILED);
    	returnVo = pushMsg(user,text);
    	AppPush appPush = new AppPush();
    	appPush.setPushText(text);
    	appPush.setUserId(user.getId());
    	appPush.setUserNickName(user.getUserNickName());
    	appPush.setUserPhone(user.getUserPhone());
    	appPush.setStatus(returnVo.getStatus());
    	appPush.setReturnMsg(returnVo.getReturnMsg());
    	this.initDefalutFields(appPush);
    	appPushDao.insert(appPush);
    	return appPush.getStatus();
    }
    
    public void pushMsg(UsersMall user,AlertType alertType,Map<String, Object> params,MsgVO msgVO) {
    	MsgType msgType = this.msgTypeService.getMsgTypeByType(alertType.getType());
    	if(msgType!=null) {
    		Jgset jgset =  this.jgsetDao.getJgsetByOrgCode(user.getOrgCode());
    		if(jgset!=null && StringUtils.isNoneBlank(jgset.getSecket(),jgset.getAppKey())) {
    			Map<String, Object> alertMap = AlertType.getAlertMap(alertType,msgVO);
    			String alert = AlertType.getAlert(alertMap,msgType.getMsgTemplate());
    			ReturnVo returnVo = new ReturnVo();
    			try {
    				JPushUtils.sendPushSingleAlias(user.getId(),alert, alert, params, jgset.getSecket(), jgset.getAppKey());
    				returnVo.setStatus(SUCCESS);
    			} catch (Exception e) {
    				returnVo.setReturnMsg(e.getMessage());
    			}
    			this.addAppPush(user, returnVo, alert,msgType);
    		}
    	}
    }
    
    public String addAppPush(UsersMall user,ReturnVo returnVo,String alert,MsgType msgType) {
    	AppPush appPush = new AppPush();
    	appPush.setPushText(alert);
    	appPush.setUserId(user.getId());
    	appPush.setUserNickName(user.getUserNickName());
    	appPush.setUserPhone(user.getUserPhone());
    	appPush.setStatus(returnVo.getStatus());
    	appPush.setReturnMsg(returnVo.getReturnMsg());
    	appPush.setIsRead(ReadType.UnRead.getState());
    	appPush.setType(msgType.getId());
    	this.initDefalutFields(appPush);
    	appPushDao.insert(appPush);
    	return appPush.getStatus();
    }
    
	public ReturnVo pushMsg( UsersMall user, String text ){
		ReturnVo returnVo = new ReturnVo();
		returnVo.setStatus(FAILED);
		
		Jgset jgset = jgsetDao.getJgsetByOrgCode(user.getOrgCode());
		//PushResult result = JPushUtils.sendPushSingleAlias(user.getId(), "123", "111", null, jgset.getSecket(), jgset.getAppKey());
		//推送消息
		JPushClient jpushClient = new JPushClient(jgset.getSecket(), jgset.getAppKey(), null, ClientConfig.getInstance());

		PushPayload payload = buildPushObject_all_alias_alert(user.getId(),text);
	    try {
	    	jpushClient.sendPush(payload);
	    	jpushClient.close();
	    	returnVo.setStatus(SUCCESS);
	    } catch (Exception e) {
	    	jpushClient.close();
	    	returnVo.setReturnMsg(e.getMessage());
	    }
	    return returnVo;
    }

    public static PushPayload buildPushObject_all_all_alert( String text ) {
        return PushPayload.alertAll(text);
    }
    
    public static PushPayload buildPushObject_all_alias_alert( String userId, String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(userId))
                .setNotification(Notification.alert(text))
                .build();
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras( String userId,String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(userId))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(text)
                        .build())
                .build();
    }
    /***
     * 根据用户Id查询所有消息分页
     * @param userId
     * @return
     */
    public List<AppPush> getMsgListByUserId(String userId,AppPushExample example,List<String> types){
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	criteria.andTypeIn(types);
    	example.setOrderByClause(" CREATE_TIME desc");
    	List<AppPush> appPushs = this.list(example);
    	return appPushs;
    }
    
    public int getCountByUserId(String userId) {
    	return this.appPushDao.selectCountByUserId(userId);
    }
    
    public int getNotReadCountByTypeId(MsgType msgType,String userId) {
    	List<MsgType> msgTypes = this.msgTypeService.getMsgTypeByParentId(msgType.getId());
    	List<String> types = new ArrayList<>();
    	if(!msgTypes.isEmpty()) {
    		for(MsgType type : msgTypes)
    			types.add(type.getId());
    	}
    	types.add(msgType.getId());
    	AppPushExample example = new AppPushExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andIsReadEqualTo(ReadType.UnRead.getState());
    	criteria.andTypeIn(types);
    	criteria.andUserIdEqualTo(userId);
    	List<AppPush> appPushs = this.list(example);
    	return appPushs.size();
    }
    
    
    public int getNotReadCount(String userId) {
    	AppPushExample example = new AppPushExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	criteria.andIsReadEqualTo(ReadType.UnRead.getState());
    	List<AppPush> appPushs = this.list(example);
    	return appPushs.size();
     }
}